package utils

import (
	"encoding/json"
	"fmt"
	"math/rand"
	"runtime/debug"
	"strconv"
	"strings"
	"time"

	"public.com/goutil/stringUtil"

	"7qule.com/sd3/CrossServer/src/common/onlinelog"
)

// 定义常量
var MinDateTime = time.Date(2000, 1, 1, 0, 0, 0, 0, time.Local)
var MaxDateTime = time.Date(3000, 1, 1, 0, 0, 0, 0, time.Local)
var GuidEmpty = "00000000-0000-0000-0000-000000000000"

// 是否为true
// data:[]byte格式的bool信息
// return:返回布尔值
func IsTrue(data []byte) bool {

	if data == nil {
		return false
	}

	if len(data) == 0 {
		return false
	}

	if data[0] == 0 {
		return false
	} else {
		return true
	}
}

// bool型转换成byte数组
// status:状态
// return:返回字节数组
func ConvertBooleanToBytes(status bool) []byte {

	if status == false {
		return []byte{0}
	} else {
		return []byte{1}
	}
}

// 将[]string组装成字符串
//
// 参数：
// numArray:源int32数组
// sep:分割字符串
//
// 返回值
// 组成的字符串
func StrSliceJoinToStr(numArray []string, sep string) string {
	str := ""
	if numArray == nil || len(numArray) == 0 {
		return str
	}

	for _, n := range numArray {
		str += fmt.Sprintf("%s%s", n, sep)
	}

	str = strings.TrimSuffix(str, sep)

	return str
}

// Int32SliceJoinToStr 将[]int32转换成字符串
// sep 分隔符
func Int32SliceJoinToStr(source []int32, sep string) (result string) {
	if source == nil || len(source) == 0 {
		return ""
	}

	for _, s := range source {
		result += fmt.Sprintf("%d%s", s, sep)
	}

	result = strings.TrimRight(result, sep)

	return
}

// 将字符串切割为[]string
//
// 参数：
// str:输入字符串
// sep:分割字符串
// removeEmpty:是否去除空字符串
//
// 返回值:
// []string
func SplitToStrSlice(s, sep string, removeEmpty bool) (resultSlice []string) {
	if len(s) == 0 {
		return make([]string, 0)
	}

	// 先按照分隔符进行切割
	strSlice := strings.Split(s, sep)

	for _, value := range strSlice {
		if removeEmpty {
			// 去除空格
			if value = strings.TrimSpace(value); value == "" {
				continue
			}
		}

		resultSlice = append(resultSlice, value)
	}

	return resultSlice
}

// 将字符串切割为[]int32
//
// 参数：
// str:输入字符串
// sep:分割字符串
// removeEmpty:是否去除空字符串
//
// 返回值:
// []string
func SplitToInt32Slice(s, sep string, removeEmpty bool) (resultSlice []int32) {
	if len(s) == 0 {
		return make([]int32, 0)
	}

	// 先按照分隔符进行切割
	strSlice := strings.Split(s, sep)

	for _, value := range strSlice {
		if removeEmpty {
			// 去除空格
			if value = strings.TrimSpace(value); value == "" {
				continue
			}
		}
		j, err := strconv.Atoi(value)
		if err != nil {
			onlinelog.ErrorLog("SplitToInt32Slice 转换错误", s, sep)
		}
		resultSlice = append(resultSlice, int32(j))
	}

	return resultSlice
}

func SplitToInt32Map(attrStr string) map[int32]int32 {
	res := make(map[int32]int32)
	if attrStr == "" {
		return res
	}

	for _, item := range stringUtil.Split(attrStr, []string{","}) {

		attr, err := stringUtil.SplitToInt32Slice(item, "|")
		if err != nil {
			return res
		} else {
			res[attr[0]] = attr[1]
		}
	}

	return res
}

// 解析时间字符串
//
// 参数：
// timeStr：时间字符串，例：12:33:12
//
//返回值:
//hour:小时
//minute:分钟
//second:秒数
func ParseTimeString(timeStr string) (hour int, minute int, second int) {
	timeSlice := strings.Split(timeStr, ":")
	if len(timeSlice) != 3 {
		return
	}

	hour, _ = strconv.Atoi(timeSlice[0])
	minute, _ = strconv.Atoi(timeSlice[1])
	second, _ = strconv.Atoi(timeSlice[2])

	return
}

// 去重
// list:列表
// return:去重后的数据
func Rm_duplicate_string(list []string) []string {
	var x []string = []string{}
	for _, i := range list {
		if len(x) == 0 {
			x = append(x, i)
		} else {
			for k, v := range x {
				if i == v {
					break
				}
				if k == len(x)-1 {
					x = append(x, i)
				}
			}
		}
	}
	return x
}

// 去重
// list:列表
// return:去重后的数据
func Rm_duplicate_int32(list []int32) []int32 {
	var x []int32 = []int32{}
	for _, i := range list {
		if len(x) == 0 {
			x = append(x, i)
		} else {
			for k, v := range x {
				if i == v {
					break
				}
				if k == len(x)-1 {
					x = append(x, i)
				}
			}
		}
	}
	return x
}

// RandomAarrayOfInt32 int32数组乱序
// arr:数组
func RandomAarrayOfInt32(arr []int32) {

	if arr == nil {
		return
	}

	if len(arr) <= 0 {
		return
	}

	rand.Seed(time.Now().UnixNano())

	for i := len(arr) - 1; i > 0; i-- {
		num := rand.Intn(i + 1)
		arr[i], arr[num] = arr[num], arr[i]
	}
}

// RandomAarrayOfString string数组乱序
// arr:数组
func RandomAarrayOfString(arr []string) {

	if arr == nil {
		return
	}

	if len(arr) <= 0 {
		return
	}

	rand.Seed(time.Now().UnixNano())

	for i := len(arr) - 1; i > 0; i-- {
		num := rand.Intn(i + 1)
		arr[i], arr[num] = arr[num], arr[i]
	}
}

// 记录错误
func LogErrorRecover() {
	if err := recover(); err != nil {
		tmsg := fmt.Sprintf("err msg:%s  stack:%s", err, debug.Stack())
		onlinelog.ErrorLog(tmsg)
	}
}

// 记录错误
func LogReqErrorRecover(r interface{}) {
	if err := recover(); err != nil {
		reqStr := ""
		if r != nil {
			b, err := json.Marshal(r)
			if err == nil {
				reqStr = string(b)
			}
		}
		tmsg := fmt.Sprintf("RequestInfo:%s .err msg:%s  stack:%s", reqStr, err, debug.Stack())
		onlinelog.ErrorLog(tmsg)
	}
}

func StringSliceIsExists(strList []string, val string) bool {

	if strList == nil {
		return false
	}

	for _, v := range strList {
		if v == val {
			return true
		}
	}

	return false
}

func SliceIsExists(n int, f func(int) bool) bool {

	for i := 0; i < n; i++ {
		if f(i) {
			return true
		}
	}

	return false
}

// GetCurWeekStartTime 得到当前周周一的零点时间
func GetCurWeekStartTime() time.Time {
	y, m, d := time.Now().Date()

	curDay := time.Now().Weekday()
	if curDay == 0 {
		curDay = 7
	}

	curDayStartTime := time.Date(y, m, d, 0, 0, 0, 0, time.Local)

	curWeekStartTime := curDayStartTime.Add(time.Hour * 24 * time.Duration(curDay-1) * -1)

	return curWeekStartTime
}

// GetCurWeekEndTime 得到当前周周天的零点时间
func GetCurWeekEndTime() time.Time {

	curWeekStartTime := GetCurWeekStartTime()

	return curWeekStartTime.Add(time.Hour * 24 * 7)
}
